package servlet;

import entity.Operator;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter( filterName = "BaseFilter")
public class BaseFilter implements Filter {
    public BaseFilter(){}
    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        System.out.println("RemoteAddr:"+httpRequest.getRequestURL());

        //在这个过滤器里面验证登录
        //只有登录后的人员才可以访问 /admin/ 路径下面的Servlet 和jsp
        String requestURL = httpRequest.getRequestURL().toString();

        String loginPage = "/admin/login.jsp";

        //是否是登录请求
        boolean isLogin = requestURL.contains("/admin/AdminLoginServlet") || requestURL.contains(loginPage);
        //是否是登录请求管理员页面
        boolean isManagePage = requestURL.contains("/admin/") || requestURL.contains("/AdminServlet");
        //System.out.println(isLogin+","+isManagePage);

        if(!isLogin && isManagePage){
            Operator operator = (Operator) httpRequest.getSession().getAttribute("loginOperator");
            if(operator==null || (operator.getCharacter()!=2L && operator.getCharacter()!=3L)){
                httpRequest.getServletContext().getRequestDispatcher("/admin/login.jsp").forward(httpRequest, response);
            }else{
                chain.doFilter(request, response);
            }
        }else{
            chain.doFilter(request, response);
        }
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
